package com.dinadi.yidi.http.interfaces;

import android.content.Context;
import android.content.Intent;

import com.dinadi.yidi.R;
import com.dinadi.yidi.http.BaseInterface;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.HttpUrl;
import com.dinadi.yidi.http.ServiceUtil;
import com.dinadi.yidi.ui.activity.LoginActivity;
import com.dinadi.yidi.ui.view.CommonDialogUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.algorithms.DesUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * author: JiaYu.He
 * Date: 2017/8/2   共用的interface
 * Time: 14:50
 */

public class CommonInterface extends BaseInterface {

    public String aa;
    private Context mContext;
    private CommonDialogUtils loginDialog;

    public CommonInterface(Context context, HttpListener listener) {
        super(context, listener);
        this.mContext = context;
    }

    public void getInterface(final String transcode, final String content) {
        //参数
        Map<String, String> param = new HashMap<>();
        param.put("transcode", transcode);
        try {
            param.put("content", DesUtil.encrypt(content));
        } catch (Exception e) {
            e.printStackTrace();
        }
        ServiceUtil.requestPostData(HttpUrl.serverHost, param, new ServiceUtil.RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {

                try {

                    aa = DesUtil.decrypt(result);
                    String errCode = JsonUtil.getFieldValue(aa, "errCode");
                    //判断是否是token失效，假如是，则关闭所有的页面，并调到登录页面
                    //有人异地登录
                    if (errCode.equals("9989")) {

                        loginDialog = new CommonDialogUtils(mContext);
                        loginDialog.setContent(R.string.agin_login);
                        loginDialog.setDialogCallback(dialogcallback);
                        loginDialog.show();

                    }
                    listener.OnSuccess(DesUtil.decrypt(result));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(String error) {
                listener.OnFail(error);

            }
        });

    }

    /**
     * 设置mydialog需要处理的事情
     */
    CommonDialogUtils.Dialogcallback dialogcallback = new CommonDialogUtils.Dialogcallback() {
        @Override
        public void dialogdo() {
            //跳转登录页面
            loginDialog.dismiss();
            Intent intent = new Intent();
            intent.setClass(mContext, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        }
    };
}

